var apiFunc = require('./constants.js');
var instanceId = '';
function commonBody(type, option) {
  var promise = new Promise((resolve, reject) => {
    if (option.promise) { // 当出现搜索调用失败使将回调函数传给第二次返回的函数
      resolve = option.promise.resolve;
      reject = option.promise.reject;
    }
    var urlBuilder = function(name) { // 从配置好的文件中搜索name对应的url
      let URL = name; // name可以直接是URL
	  console.log(name)
      var api = apiFunc();
      // 所有请求在constants.js配置，统一管理
      Object.keys(api).forEach(item => {
        if (item.indexOf(name) !== -1 && item.length === name.length) {
          URL = api.server + api[`${item}`];
		  console.log('url:'+URL)
		  
        }
      });
      // console.log('url: ' + URL);
      return URL
    }
    var headerBuilder = function(header = {}) { // 构建请求头
      // 微信小程序网络请求接口
      let requestHeader = {
        'channel': 'smallapplication',
        'content-type': 'application/x-www-form-urlencoded',
        'sysName': 'zxlmp',
        'lang': 'zh_CN',
        'clientId': 'client.wx.microapp',
        'instanceId': instanceId
      };
      if (uni.getStorageSync('sessionId')) {
        requestHeader.Cookie = 'SESSION=' + uni.getStorageSync('sessionId');
      }
      Object.assign(requestHeader, header)
      return requestHeader
    }
    // 不用全局的加载器，本页面自己写是rejectLoadingTip为true
    if (!option.rejectLoadingTip) {
      uni.showToast({
        title: '正在加载',
        mask: true,
        icon: 'loading',
        duration: 10000
      });
    }
    uni.request({
      url: urlBuilder(option['name']),
      data: option['params'] || {},
      method: type,
      header: headerBuilder(option['header']),
      success: res => {
        if (!option.rejectLoadingTip) {
          uni.hideToast();
        }
        let _response = res.data;
        if(_response.msg === '搜索服务调用失败') {
          if (!option.promise) {
            console.warn('搜索服务调用失败，已经重试！！！')
            option.promise = { resolve, reject };
            get(option);
          } else {
            resolve(_response);
          }
          return
        }
				if(_response.msg === '请登录账号') {
				  uni.reLaunch({
				  	url: '/pages/login/index'
				  })
				  return
				}
        
        if (_response.result !== 'success' && !option.rejectErrorTip) {
          uni.stopPullDownRefresh();
          uni.showModal({
            title: '温馨提示',
            showCancel: false,
            content: _response.msg || '网络连接超时，请稍后重试！',
            success (res) {
              if (res.confirm) {
                resolve(_response);
                console.log('用户点击确定');
              } else if (res.cancel) {
                console.log('用户点击取消');
              }
            }
          });
        } else {
          resolve(_response);
        }
      },
      fail: (res) => {
        uni.stopPullDownRefresh();
        uni.hideToast();
        // 错误提醒
        uni.showToast({
          title: '网络连接超时，请稍后重试！',
          mask: true,
          icon: 'none',
          duration: 2000
        });
        console.log(res);
        console.log('网络错误');
        reject(res.data);
      }
    });
  });
  return promise;
}
// 微信post请求
function post (option = {}) {
  return commonBody('POST', option)
}
// 微信get请求
function get (option = {}) {
  return commonBody('GET', option)
}
// 微信delete请求
function del (option = {}) {
  let _option = {}; // 将params拼接出URL参数
  var api = apiFunc();
  Object.keys(api).forEach(item => {
    if (item.indexOf(option['name']) !== -1 && item.length === option['name'].length) {
      _option.name = api.server + api[`${item}`];
      Object.keys(option.params).forEach(function(item, index) {
        if (index === 0) {
          _option.name += '?' + item + '=' + option.params[item]
        } else {
          _option.name += '&' + item + '=' + option.params[item]
        }
      })
    }
  });
  return commonBody('DELETE', _option)
}
// 微信put请求
function put (option = {}) {
  return commonBody('PUT', option)
}
export default function(domain, prefix, _instanceId){
	apiFunc = apiFunc(domain, prefix);
	instanceId = _instanceId;
	return {
		POST: post,
		GET: get,
		DELETE: del,
		PUT: put
	};
}
